using System;
using Game.Core;
using Game.Core.Loader;
using Game.Main.Event;
using UnityEngine;
using UnityEngine.UI;

namespace Game.Main.View
{
	public class ImageContainer
	{
		public string path;

		public string resourceName;

		public string spriteName;

		public Transform transform;

		public Transform parent;

		public Image image;

		private int layer = 5;

		private SpriteLoader loader;

		public Action completeAction;

		private Color color = Color.white;

		public ImageContainer(Transform transform = null)
		{
			this.transform = transform;
			image = transform.gameObject.GetComponent<Image>();
			if (image != null)
			{
				image.enabled = false;
			}
		}

		public ImageContainer(string path, string resourceName, Transform transform = null, string spriteName = "", int layer = 5)
		{
			this.path = path;
			this.resourceName = resourceName;
			this.transform = transform;
			image = transform.gameObject.GetComponent<Image>();
			if (image != null)
			{
				image.enabled = false;
			}
			this.spriteName = spriteName;
			this.layer = layer;
		}

		public void Init()
		{
			if (loader != null)
			{
				loader.Destroy();
				loader = null;
			}
			if (!path.Equals(string.Empty))
			{
				loader = new SpriteLoader(path, resourceName);
				loader.Bind(LoadEvent.LOAD_COMPLETE, OnLoadComplete);
				loader.Load();
			}
		}

		public void SetColor(Color color)
		{
			this.color = color;
			if (image != null)
			{
				image.color = color;
			}
		}

		public void SetMaterial(Material mat)
		{
			if (image != null)
			{
				image.material = mat;
			}
		}

		public void SetImage(string path, string resourceName, string spriteName = "", int layer = 5)
		{
			if (this.path == path && this.resourceName == resourceName && this.spriteName == spriteName)
			{
				if (completeAction != null)
				{
					completeAction();
				}
				return;
			}
			this.path = path;
			this.resourceName = resourceName;
			this.spriteName = spriteName;
			this.layer = layer;
			image.color = new Color(1f, 1f, 1f, 0f);
			Init();
		}

		private void OnLoadComplete(BaseEvent evt)
		{
			if (transform == null)
			{
				transform = new GameObject().transform;
				transform.name = resourceName;
				transform.gameObject.layer = layer;
				transform.SetParent(parent, false);
				image = transform.gameObject.AddComponent<Image>();
				transform = image.transform;
			}
			else if (image == null)
			{
				image = transform.gameObject.GetComponent<Image>();
			}
			if (spriteName.Equals(string.Empty))
			{
				image.sprite = loader.resource[0];
			}
			else
			{
				for (int i = 0; i < loader.resource.Length; i++)
				{
					if (loader.resource[i].name.Equals(spriteName))
					{
						image.sprite = loader.resource[i];
						break;
					}
				}
			}
			image.color = color;
			image.enabled = true;
			image.SetNativeSize();
			loader.Destroy();
			loader = null;
			if (completeAction != null)
			{
				completeAction();
			}
		}
	}
}
